package com.cn.main.proxy;

import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.context.annotation.Import;
import org.springframework.context.annotation.ImportBeanDefinitionRegistrar;
import org.springframework.core.type.AnnotationMetadata;
import org.springframework.util.ClassUtils;
import org.springframework.util.StringUtils;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

/**
 * @aothor chenyuncong
 * @Date 2022/8/29 下午10:21
 */
@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Import(EnableProxyBeanScan.ProxyBeanDefinitionRegistrar.class)
public @interface EnableProxyBeanScan {
    String[] basePackages() default {};

    class ProxyBeanDefinitionRegistrar implements ImportBeanDefinitionRegistrar {
        @Override
        public void registerBeanDefinitions(AnnotationMetadata importingClassMetadata, BeanDefinitionRegistry registry) {
            ProxyInterfaceBeanBeanDefinitionScanner scanner = new ProxyInterfaceBeanBeanDefinitionScanner(registry);
            scanner.scan(getBasePackages(importingClassMetadata));
        }

        private String[] getBasePackages(AnnotationMetadata importingClassMetadata){
            Map<String, Object> attributes = importingClassMetadata.getAnnotationAttributes(EnableProxyBeanScan.class.getCanonicalName());
            Set<String> basePackages = new HashSet();
            String[] basePackagesArr = (String[])((String[])attributes.get("basePackages"));
            for(String item: basePackagesArr){
                if(StringUtils.hasText(item))
                    basePackages.add(item);
            }

            if (basePackages.isEmpty()) {
                basePackages.add(ClassUtils.getPackageName(importingClassMetadata.getClassName()));
            }

            return basePackages.toArray(new String[basePackages.size()]);
        }
    }
}
